/**
 * 初始化整体余额消耗变化趋势
 */
define(function(){
    var ec=require('echarts');
    require('echarts/chart/line');
    require('echarts/chart/bar');

    var zrnumber = require('echarts/util/number');

    var myChart = ec.init(document.getElementById('inventory_balance'));
    
    var dateGrp = '';
    var option_line = {
    	    tooltip : {
    	        trigger: 'axis'
    	    },
    	    dataZoom : {
    	        show : true,
    	        realtime: true,
    	        height:15,
    	        start : 50,
    	        end : 100
    	    },
    	    legend: {
    	        data:['全部','会员','非会员']
    	    },
    	    toolbox: {
    	        show : true,
    	        orient:'vertical',
    	        y:'bottom',
    	        feature : {
    	            mark : {show: true},
    	            dataView : {show: true, readOnly: false},
    	            magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
    	            restore : {show: true},
    	            saveAsImage : {show: true}
    	        }
    	    },
    	    calculable : true,
    	    xAxis : [
    	        {
    	            type : 'category',
    	            boundaryGap : true,
    	            data : [],
    	            axisLabel:{formatter:function(value){
                        return value;
                    }}
    	        }
    	    ],
    	    yAxis : [
	    	        {
	                type : 'value',	              
	            },
	            {
	                type : 'value',             
	            }
    	    ],
    	    series : [
    	        {
    	            name:'全部',
    	            type: 'line',
                    smooth: true,
                    symbol:"none",   	           
    	            data:[]
    	        },
    	        {
    	            name:'会员',
    	            type: 'line',
                    smooth: true,
                    symbol:"none",    	            
    	            data:[]
    	        },
    	        {
    	            name:'非会员',
    	            type:'line',
    	            smooth: true,
    	            symbol:"none",	           
    	            data:[]
    	        }
    	    ]
    	};

    /**
     * 根据指标显示日数据
     * @param eventType= 2:第一次加载, 1:切换日，周，月刷新 , 0: 添加对比后又重新选择指标
     */
    
    var targetMap = {'总充值':'adcash_deposit','总消耗':'adcash_consume','总余额':'adcash_balance','消耗周期':'consume_circle','消耗率':'consume_rate','总客户数':'user_num','消费客户数':'cost_user_num','余额客户数':'balance_user_num','充值客户数':'deposit_user_num','开通率':'open_rate','人均消耗':'avg_consume','人均充值':'avg_deposit','人均余额':'avg_balance'};

    function show(eventType){
    	dateGrp = $('#balance_option').attr('statType');
        var businessName = $('#businessName').val();
        var cityName = $('#cityName').val();
        var cateName = $('#balance_cate').val();
        var proType = $('#indexType').val();
        var statType = $('#balance_option').attr('statType');
        myChart.showLoading({
            text: '正在努力的读取数据中...'
        });
        
                $.ajax({
            url: '/dashboard/homePage/ajax/inventoryBalance',
            type: 'post',
            async: true,
            data:{"businessName": businessName, "cityName":cityName,"cateName":cateName,"indexType":targetMap[proType],"statType":statType,"dataType":"chart"},
            dataType: 'json',
            success: function(data, textStatus) {
            	//console.log(data);
            	if(data.time == ""){
            		myChart.showLoading({
                        text: '目前暂无该数据'
                    });
            		return ;
            	}
            	option_line.xAxis[0].data = data.time;
            	option_line.series[0].data = data.all;
            	option_line.series[1].data = data.is_vip;
            	option_line.series[2].data = data.no_vip;
            	option_line.tooltip.formatter=tooltipFunc;    
            	
            	//区域缩放
                var datezoom_local={
                    day:{start:(1-31/data.time.length)*100,end:100},
                    week:{start:(1-12/data.time.length)*100,end:100},
                    month:{start:0,end:100},
                };
                //少于31个点，全显
                if(data.time.length<31){
                    datezoom_local={
                        day:{start:0,end:100},
                        week:{start:0,end:100},
                        month:{start:0,end:100},
                    };
                }

                if(eventType == 1 || eventType == 2){
                    if('month' == statType){
                        option_line.xAxis[0].axisLabel.formatter=function(value){ return value.substr(0,4)+"年"+value.substr(4,2)+"月"; } ;
                    }else{
                        option_line.xAxis[0].axisLabel.formatter=function(value){ return value; } ;
                    }
                   
                    if(eventType == 1 && myChart.component.dataZoom){
                        option_line.dataZoom=datezoom_local[statType];
                        myChart.component.dataZoom.absoluteZoom(datezoom_local[statType]);
                        option_line.dataZoom.show=true;
                    }else if(eventType == 2){
                        option_line.dataZoom=datezoom_local[statType];
                        option_line.dataZoom.show=!$('#time_checkbox_balance').is(":checked");
                    }
                    myChart.setOption(option_line,true);
                }else if(eventType == 0){
                   myChart.component.dataZoom=compDataZoom_old;
                    myChart.setOption(option_line,true);
                    if($('#time_input_balance').val()){
                        EC.addCompare($('#time_input_balance').val());
                    }
                }
                // myChart.clear();
                myChart.hideLoading();
            },
            error : function() {
                myChart.hideLoading();
            }
        });
    }
    
    var ecConfig = require('echarts/config');
    //鼠标click事件
    function eventClick(param){
        var click_date = '2014-01-01';
        if (typeof param.seriesIndex != 'undefined') {
            click_date = param.name;
        }
        loadTableData(click_date);
    }
    myChart.on(ecConfig.EVENT.CLICK, eventClick);
    //加载27个直销城市当天的数据，, 0:字符, 1:数字, 2:百分比
    
   // var show_cols = {"is_vip":0,"adcash_deposit":1,"adcash_deposit_chain":2,"adcash_consume":1,"adcash_consume_chain":2,"adcash_balance":1,"adcash_balance_chain":2,"consume_circle":1,"consume_circle_chain":2,"consume_rate":1,"consume_rate_chain":2,"user_num":1,"user_num_chain":2,"cost_user_num":1,"cost_user_num_chain":2,"balance_user_num":1,"balance_user_chain":2,"deposit_user_num":1,"deposit_user_chain":2,"open_rate":1,"open_rate_chain":2,"avg_consume":1,"avg_consume_chain":2,"avg_deposit":1,"avg_deposit_chain":2,"avg_balance":1,"avg_balance_chain":2};
  
    var show_cols = {"is_vip":0,"adcash_deposit":1,"adcash_deposit_chain":2,"adcash_consume":1,"adcash_consume_chain":2,"adcash_balance":1,"consume_circle":1,"consume_rate":1,"user_num":1,"cost_user_num":1,"balance_user_num":1,"deposit_user_num":1,"open_rate":1,"open_rate_chain":2,"avg_deposit":1,"avg_deposit_chain":2,"avg_balance":1,"avg_balance_chain":2};
    function loadTableData(stat_date){
    	
        dateGrp = $('#balance_option').attr('statType');
        var businessName = $('#businessName').val();
        var cityName = $('#cityName').val();
        var cateName = $('#balance_cate').val();
        var proType = $('#indexType').val();
        var statType = $('#balance_option').attr('statType');
        
        $.ajax({
            url: '/dashboard/homePage/ajax/inventoryBalance',
            type: 'post',
            async: true,
            data:{"businessName": businessName, "cityName":cityName,"cateName":cateName, "indexType":targetMap[proType],"statType":statType,"dataType":"table","dateVal":stat_date},
            dataType: 'json',
            success: function(data, textStatus) {
            	//console.log(data);
                var resultList = data.dataList;
                var htmlRows = "";
                 
                $.each(resultList,function(i,vo){
                    htmlRows += "<tr>";

                    $.each(show_cols,function(col,colType){
                        switch(colType){
                            case 0:
                                htmlRows += "<td>";
                                if(vo[col]==0){
                                	 htmlRows += "非会员";
                                }else if(vo[col]==1){
                                	htmlRows += "会员";
                                }else{
                                	htmlRows += "全部";
                                }
                                htmlRows += "</td>";
                                break;
                            case 1:
                                htmlRows += "<td>";
                                htmlRows += zrnumber.addCommas(vo[col]);
                                htmlRows += "</td>";
                                break;
                            case 2:
                                htmlRows += getRate(vo[col]);
                                break;
                            case 3:
                                htmlRows += "<td>";
                                htmlRows += parseFloat(vo[col]).toFixed(2)+"%";
                                htmlRows += "</td>";
                                break;                                   
                        }
                    });

                    htmlRows += "</tr>";
                });

                $('#balanceTotalTable tr:gt(0)').remove();
                $('#balanceTotalTable_date').text(stat_date.replace(/\-/g,"."));
                $('#balanceTotalTable').append(htmlRows);
            },
            error : function() {

            }
        }); 
    }
    
    
    function  tooltipFunc(params, ticket, callback){
        var dateVal = formatShowDate(params[0].name);
        var curOption = option_line;
        var index_current=getIndexByName(curOption.xAxis[0].data,params[0].name);

        var result='<table class="table-center">';
        result+='<tr><td>'+dateVal+'</td><td>';
        var isStatDay = isDay(); 
        if(isStatDay)
            result += getWeekDay(dateVal);
        result += '</td>';
        if(isStatDay)
            result +="<td>日环比</td><td>周同比</td>";
        else if(isWeek())
            result += "<td>周环比</td>";
         else if(isMonth())
            result += "<td>月环比</td><td>月同比</td>";
        result += '</tr>';


        $(params).each(function(index,para){
            result+='<tr><td>'+para.seriesName+'</td><td>'+zrnumber.addCommas(parseInt(para.data))+'</td>';
            var seriesIndex = para.seriesIndex;
            var day_td="<td>--</td>";
            //日周月 环比(前一日周月)
            if(index_current-1>=0){
                var data_yesday = null;
                data_yesday= curOption.series[seriesIndex].data[index_current-1];                
                if(data_yesday != null){
                    var s=(((para.data/data_yesday)-1)*100).toFixed(2);
                    if(data_yesday == 0 ){
                  	  if(para.data>data_yesday){
                  		  day_td='<td style="color: orangered;">100%&#8593</td>';
                  	  }
                  	  else if(para.data<data_yesday){
                  		  day_td='<td style="color: greenyellow;">-100%&#8595</td>';
                  	  } else{
                  		  day_td='<td style="color: greenyellow;">0%</td>';
                  	  } 
                    }else {
                    
	                      if(s>0){
	                          day_td='<td style="color: orangered;">'+s+'%&#8593</td>';
	                      }else{
	                          day_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
	                      }
                    }
                }
            }
            result += day_td;
            //周同比(日)
             if(isStatDay){
                 var week_td='<td>--</td>';
                 if(index_current-7>=0){
                     data_week= curOption.series[seriesIndex].data[index_current-7];
                     var s=(((para.data/data_week)-1)*100).toFixed(2);
                     if(data_yesday == 0 ){
                   	  if(para.data>data_week){
                   		 week_td='<td style="color: orangered;">100%&#8593</td>';
                   	  }
                   	  else if(para.data<data_week){
                   		 week_td='<td style="color: greenyellow;">-100%&#8595</td>';
                   	  } else{
                   		 week_td='<td style="color: greenyellow;">0%</td>';
                   	  } 
                     }else {
                     
	                      if(s>0){
	                    	 week_td='<td style="color: orangered;">'+s+'%&#8593</td>';
	                      }else{
	                    	 week_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
	                      }
                     }
                 }
                 result += week_td;
             }
            //去年同月
            if(isMonth()){
                var td='<td>--</td>';
                var data_last = null;
                if(index_current-12>=0){
                   data_last= option_line.series[seriesIndex].data[index_current-12];
               }
                if(data_last != null){
                   var s=(((para.data/data_last)-1)*100).toFixed(2);
                   if(data_yesday == 0 ){
                  	  if(para.data>data_last){
                  		 td='<td style="color: orangered;">100%&#8593</td>';
                  	  }
                  	  else if(para.data<data_last){
                  		 td='<td style="color: greenyellow;">-100%&#8595</td>';
                  	  } else{
                  		 td='<td style="color: greenyellow;">0%</td>';
                  	  } 
                    }else {
                    
	                      if(s>0){
	                    	 td='<td style="color: orangered;">'+s+'%&#8593</td>';
	                      }else{
	                    	 td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
	                      }
                    }
               }
               result += td;
           }                   
              result += '</tr>';
        });
        result+='</table>';
        return result;
    }        
    
function formatShowDate(yyyymmdd){
        //  var dateGrp = $('#mSrc3_option').attr('dateGrp');
    	//var dateGrp = 'stat_date';
                
        if('day'==dateGrp){
            return yyyymmdd;
        }else if('week'==dateGrp){
            return yyyymmdd;
        }else if('month'==dateGrp){
            return yyyymmdd.substr(0,4)+"年"+yyyymmdd.substr(4,2)+"月";
        }
    }

function isDay(){
        //var dateGrp = $('#mSrc3_option').attr('dateGrp');
        if('day'==dateGrp){
            return true;
        }
        return false;
    }

function isWeek(){
        //var dateGrp = $('#mSrc3_option').attr('dateGrp');
        if('week'==dateGrp){
            return true;
        }
        return false;
    }

function isMonth(){
        //var dateGrp = $('#mSrc3_option').attr('dateGrp');
        if('month'==dateGrp){
            return true;
        }
        return false;
    }

var zrUtil = require('zrender/tool/util');
  //console.log(zrUtil);

function getShowDays(){
        return compDataZoom_old.option.xAxis[0].data;
    }
    
function addCompare(time){
	   // console.log(option_line);
        time=formatTime(time);
        var copy=zrUtil.clone(option_line);
        var index_time=getIndexByName(option_line.xAxis[0].data,time);
        if(index_time == -1){
        	alert("当天没有数据，无法进行对比！");
        	return ;
        }
        var index_show=getIndexByName(option_line.xAxis[0].data,getShowDays()[0]);
        var length=getShowDays().length;
        setCompareXaxis(copy,index_time,index_show,length);
        var index=0;
        //选中对比时，再次选择指标，需要记忆图例的选择状态
        $.each(legend_SelectedMap,function(key,value){
            //判断是否在当前图例值中，应为echarts会把"对比时间段"也放入SelectedMap
            if($.inArray(key,option_line.legend.data) != -1){
                if(value){
                    return false;
                }
                index++;
            }     
        });
        
        if(index<option_line.legend.data.length){
            setCompareSeries(copy,index,index_time,index_show,length);
            setCompareLegend(copy);
            setCompareTooltip(copy);
            delete copy.dataZoom;
            myChart.restore();
            myChart.setOption(copy,true);
        }

    }

function setCompareLegend(copy){
        copy.legend= {
            data:[copy.series[0].name, copy.series[1].name],
            selectedMode:false
        }
    }

var compDataZoom_old;
var legend_SelectedMap={};  //需要记忆图例的选择状态
function hideDataZoom(){
        legend_SelectedMap=myChart.component.legend.getSelectedMap();
        compDataZoom_old=myChart.component.dataZoom;    //记忆缩放
        option_line.dataZoom.show=false;
        myChart.setOption(option_line,false);
    }

function removeCompare(){
        //恢复缩放
        myChart.component.dataZoom=compDataZoom_old;
        option_line.dataZoom.show=true;
        //去掉对比时恢复图例的选择状态
        $.each(legend_SelectedMap,function(key,value){
            if($.inArray(key,option_line.legend.data) != -1){
                myChart.component.legend.setSelected(key,value);
            }else{
                myChart.component.legend.setSelected(key,false);
            }
        });
        myChart.setOption(option_line,true);
    }


function setCompareTooltip(copy){
        copy.series[1]&&copy.series[1].tooltip&&(copy.series[1].tooltip={show:false});
        copy.series[2]&&copy.series[2].tooltip&&(copy.series[2].tooltip={show:false});
        copy.series[3]&&copy.series[3].tooltip&&(copy.series[3].tooltip={show:false});

        copy.tooltip.formatter=function(params, ticket, callback){
            var date_current=params[0][1];
            var data_current=params[0][2];
            var index_current=getIndexByName(copy.xAxis[0].data,date_current);
            
            var dateVal = formatShowDate(date_current);
            var result='<table class="table-center">' +
                '<tr><td>'+dateVal;
            //是日要显示周几
            if(isDay())
                 result += ' ('+getWeekDay(dateVal)+')';
            result += '</td><td>'+zrnumber.addCommas(data_current)+'</td></tr>';
            if(copy.series[1]){
                var data_compare=copy.series[1].data[index_current];
                var s=(((data_current-data_compare)/data_compare)*100).toFixed(2);
                dateVal = formatShowDate(copy.xAxis[1].data[index_current]);
                result+='<tr><td>'+dateVal;
                if(isDay())
                    result += ' ('+getWeekDay(dateVal)+')';
                result += '</td><td>'+zrnumber.addCommas(data_compare)+'</td></tr>';
                if(s>0){
                    result+='<tr><td>变化</td><td style="color: orangered">'+s+'%&#8593</td></tr>';
                }else{
                    result+='<tr><td>变化</td><td style="color: greenyellow">'+s+'%&#8595</td></tr>';
                }
            }
            result+='</table>';
            return   result;
        }
    }

function  setCompareSeries(copy,index,index_time,index_show,length){
        copy.series=[];
        //原来数据
        copy.series.push(zrUtil.clone(option_line.series[index]));
        copy.series[0].type='line';
        copy.series[0].data=option_line.series[index].data.slice(index_show,index_show+length);
        delete  copy.series[0].stack;
        delete  copy.series[0].itemStyle;
        //对比数据
        copy.series.push(zrUtil.clone(option_line.series[index]));
        copy.series[1].type='line';
        copy.series[1].name="对比时间段";
        copy.series[1].xAxisIndex=1;
        delete  copy.series[1].stack;
        delete  copy.series[1].itemStyle;

        copy.series[1].data=option_line.series[index].data.slice(index_time,index_time+length);
        if(length>31){return}
        //对比柱
        copy.series.push({
            tooltip:{show:false},
            show:false,
            name: '对比时间段1',
            type: 'bar',
            stack: '1',
            barWidth:3,
            xAxisIndex:1,
            itemStyle:{
                normal:{
                    color:'rgba(0,0,0,0)'
                },
                emphasis:{
                    color:'rgba(0,0,0,0)'
                }
            },
            data: function(){
                var i=0;
                return $.map(copy.series[1].data,function(val){
                    var tt=copy.series[0].data[i++];
                    if(toNum(val)<toNum(tt)){
                        return val;
                    }else{
                        return tt;
                    }
                })
            }()
        });
        copy.series.push({
            tooltip:{show:false},
            name: '变化',
            type: 'bar',
            stack: '1',
            xAxisIndex:1,
            data: function(){
                var i=0;
                return $.map(copy.series[1].data,function(val){
                    var tt=copy.series[0].data[i++];
                    if(toNum(val)<toNum(tt)){
                        return tt-val;
                    }else{
                        return {value : val-tt, itemStyle:{ normal:{color:'red'}}};
                        //return val-tt;
                    }
                })
            }()
        });
    }

function setCompareXaxis(copy,index_time,index_show,length){
        copy.xAxis=[];
        copy.xAxis.push(zrUtil.clone(option_line.xAxis[0]));
        copy.xAxis.push(zrUtil.clone(option_line.xAxis[0]));
        copy.xAxis[0].data=option_line.xAxis[0].data.slice(index_show,index_show+length);
        copy.xAxis[1].data=option_line.xAxis[0].data.slice(index_time,index_time+length);
    }      
    
//双Y轴时要重新设置Y轴名称
function setCompareYaxis(copy,index){
    var yAxisName = copy.yAxis[index].name;
    copy.yAxis.forEach(function(value){
        value.name=yAxisName;
    }); 
}

function getIndexByName(data,name) {
        var dataLength = data.length;
        for (var i = 0; i < dataLength; i++) {
            if (data[i] == name || typeof data[i].value != 'undefined' && data[i].value == name) {
                return i;
            }
        }
        return -1;
    }
    
    
function formatTime(time){
        return time;
    }

function getAllDays(){
        return option_line.xAxis.data||option_line.xAxis[0].data;
    }
	

$(":button.btn_balance[statType]").click(function(){
    
 	 changeDateGrp(this);
     $('#time_checkbox_balance').attr('checked',false);
     $('#time_input_balance').val('');
     $('#time_input_balance').attr('disabled','');
     if($(this).attr('statType')=='week'){
         $('#time_input_balance').parent().css('visibility',"hidden");
     }else{
         $('#time_input_balance').parent().css('visibility',"visible");
     }
     EC.show(1);
 });

//时间勾选框事件
$('#time_checkbox_balance').change(function(e){
    var input=$('#time_input_balance');
    if(!input)return;
    if($(this).is(":checked")){
        input.removeAttr('disabled');
        input.attr('placeholder','选择时间起点');               
        EC.hideDataZoom();
        setDatePicker_v1(EC, $('#balance_option').attr('statType'),input);
    }else{
        input.val('');
        input.attr('disabled','');
        input.attr('placeholder','添加对比');               
        EC.removeCompare();
    }
});

//对比时间选择事件
$('#time_input_balance').datepicker().on('changeDate',function(e){
	
	EC.addCompare(e.format());
    
});
//字符串转数字
function toNum(n){
    var num = new Number(n);
    return num.valueOf();
};
$("#balance_btn").click(function(){	
	var type = 2;
    if($('#time_checkbox_balance').is(":checked"))
        type=0;        
    show(type);
});	

 var EC={
        show:show,
        resize:function(){myChart.resize();},
        hideDataZoom:hideDataZoom,
        removeCompare:removeCompare,
        getShowDays:getShowDays,
        getAllDays:getAllDays,
        addCompare:addCompare
    };
    
    return EC;    
});

